package com.yuke.cloud.service.uac.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.core.annotation.LogAnnotation;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.uac.dto.CheckEmployeeCode;
import com.yuke.cloud.service.uac.dto.GroupBindUserDto;
import com.yuke.cloud.service.uac.dto.GroupBindUserReqDto;
import com.yuke.cloud.service.uac.entity.AccUserGroup;
import com.yuke.cloud.service.uac.service.AccEmployeeGroupService;
import com.yuke.cloud.service.uac.service.AccUserGroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
* Created by wg on 2018/09/15.
*/
@Api(value = "WEB - AccUserGroupController", tags = "处理AccUserGroup相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/acc/user_group")
public class AccUserGroupController extends BaseController {
    @Resource
    private AccUserGroupService accUserGroupService;

    @Resource
    private AccEmployeeGroupService accEmployeeGroupService;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "accUserGroup", value = "该数据记录的POJO") @RequestBody AccUserGroup accUserGroup) {
        if (accUserGroup != null){
            AccUserGroup bbb = new AccUserGroup();
            bbb.setUserId(accUserGroup.getUserId());
            List<AccUserGroup> aaa = accUserGroupService.select(bbb);
            if (aaa!=null || aaa.size()>0){
                logger.error("该用户已绑定有部门！");
               return WrapMapper.error("该用户已绑定有部门！");
            }
            logger.info("新增一条记录accUserGroupService.save(accUserGroup)");
            accUserGroupService.save(accUserGroup);
            return WrapMapper.ok();
        }
        return WrapMapper.error("传入参数为空！");

    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        accUserGroupService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "accUserGroup", value = "需要修改的内容") @RequestBody AccUserGroup accUserGroup) {
        accUserGroupService.update(accUserGroup);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<AccUserGroup> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        AccUserGroup accUserGroup = accUserGroupService.findById(id);
        return WrapMapper.ok(accUserGroup);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<AccUserGroup>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<AccUserGroup> list = accUserGroupService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 组织绑定用户页面数据
     *
     * @param groupId the group id
     *
     * @return the group bind user page info
     */
    @GetMapping(value = "/getBindUser/{groupId}")
    @ApiOperation(httpMethod = "GET", value = "获取组织绑定用户页面数据")
    public Wrapper<GroupBindUserDto> getGroupBindUserPageInfo(@ApiParam(name = "groupId", value = "组织id") @PathVariable Long groupId) {
        logger.info("查询组织绑定用户页面数据 groupId={}", groupId);

        LoginAuthDto loginAuthDto = super.getLoginAuthDto();
        Long currentUserId = loginAuthDto.getUserId();
        GroupBindUserDto bindUserDto = accUserGroupService.getGroupBindUserDto(groupId, currentUserId);
        return WrapMapper.ok(bindUserDto);
    }

    /**
     * 组织绑定用户，一个用户只能绑定一个部门
     *
     * @param groupBindUserReqDto the group bind user req dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/bindUser")
    @LogAnnotation
    @ApiOperation(httpMethod = "POST", value = "组织绑定用户")
    public Wrapper bindUser4Role(@ApiParam(name = "uacGroupBindUserReqDto", value = "组织绑定用户") @RequestBody GroupBindUserReqDto groupBindUserReqDto) {
        logger.info("组织绑定用户...  groupBindUserReqDto={}", groupBindUserReqDto);

        LoginAuthDto loginAuthDto = super.getLoginAuthDto();

        accUserGroupService.bindUacUser4Group(groupBindUserReqDto, loginAuthDto);
        return WrapMapper.ok();
    }

    /**
     * 根据用户ID和部门ID查询
     *
     * @param userId the userId
     * @param groupId the groupId
     *
     * @return the wrapper
     */
    @GetMapping(value = "/getUserGroup")
    @LogAnnotation
    @ApiOperation(httpMethod = "GET", value = "根据用户ID和部门ID查询")
    public Wrapper getUserGroup(@ApiParam(name = "userId", value = "用户ID") @RequestParam("userId") Long userId,
                                @ApiParam(name = "groupId", value = "部门ID") @RequestParam("groupId") Long groupId) {
        List<AccUserGroup> list = accUserGroupService.getByUserIdAndGroupId(userId, groupId);
        if (list.size() > 1) {
            return WrapMapper.error("数据不唯一！");
        }

        if (list.size() == 0) {
            return WrapMapper.error("没有数据！");
        }

        return WrapMapper.ok(list.get(0));
    }

    /**
     * 校验员工号唯一性.
     *
     * @param checkEmployeeCode the check user phone dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkEmployCode")
    @ApiOperation(httpMethod = "POST", value = "校验员工号唯一性")
    public Wrapper<Boolean> checkUserPhone(@ApiParam(name = "CheckEmployeeCode", value = "校验员工号唯一性Dto") @RequestBody CheckEmployeeCode checkEmployeeCode) {
        logger.info(" 校验员工号唯一性 checkEmployeeCode={}", checkEmployeeCode);
        Long id = checkEmployeeCode.getUserId();
        String employeeCode = checkEmployeeCode.getEmployeeCode();
        Example example = new Example(AccUserGroup.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("employeeCode", employeeCode);

        if (id != null) {
            criteria.andNotEqualTo("userId", id);
        }

        int result = accEmployeeGroupService.selectCountByExample(example);
        return WrapMapper.ok(result < 1);
    }

    /**
     * 校验员工号唯一性.
     *
     * @param checkEmployeeCode the check user phone dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkUserId")
    @ApiOperation(httpMethod = "POST", value = "校验员工号唯一性")
    public Wrapper<Boolean> checkUserId(@ApiParam(name = "CheckEmployeeCode", value = "校验员工号唯一性Dto") @RequestBody CheckEmployeeCode checkEmployeeCode) {
        logger.info(" 校验员工号唯一性 checkUserId={}", checkEmployeeCode);
        Long id = checkEmployeeCode.getUserId();

        Example example = new Example(AccUserGroup.class);
        Example.Criteria criteria = example.createCriteria();
        if (id != null) {
            criteria.andNotEqualTo("userId", id);
        }

        int result = accEmployeeGroupService.selectCountByExample(example);
        if (result < 1){
            return WrapMapper.ok();
        }
        return WrapMapper.error("一个用户只能绑定一个部门，该用户已绑定部门，之前绑定的部门将解绑！");
    }
}
